package.path = '/usr/local/Cellar/openresty/1.13.6.1/lualib/resty/?.lua;/opt/soft/nginx/lualib/resty/?.lua;'
package.cpath = '/usr/local/Cellar/openresty/1.13.6.1/lualib/?.so;/opt/soft/nginx/lualib/?.so;;'

local cjson = require "cjson"

function get_cookies()
  local cookies = ngx.header["Set-Cookie"] or {}
  if type(cookies) == "string" then
    cookies = {cookies}
  end
  return cookies
end


function add_cookie(cookie)
  local cookies = get_cookies()
  table.insert(cookies, cookie)
  ngx.header['Set-Cookie'] = cookies
end

local host_name = ngx.var.host_name
if not host_name then
	host_name = ngx.req.get_headers()["Host"]
end

local arg = ngx.req.get_uri_args()

if ngx.var.request_uri == '/favicon.ico' then
	return
end

if(string.find(ngx.var.request_uri,'^/css')==1 or string.find(ngx.var.request_uri,'^/js')==1) then
	return
end

local notLogin = true


local cdp_key = ngx.var.cookie_cdp_key
local cdp_user = ngx.var.cookie_cdp_user



if(cdp_key and cdp_user and #cdp_key>1 and #cdp_user>1) then
	local res = ngx.location.capture('/userinfo')
	if res.status==200 then
		local resbody = cjson.decode(res.body)
		if  resbody.success then
			notLogin = false
		end
	end	
end




if notLogin then
	ngx.log(ngx.INFO, 'curr path = '..ngx.var.request_uri)
	return ngx.redirect("http://bigdata.58.com/login?url=http://" .. host_name .. ngx.var.uri)
end